<template>
  <el-select
      v-loading="loading"
      v-model="value"
      :disabled="disabled"
      :clearable="!field.not_null"
      :teleported="false"
      filterable
      :value-on-clear="null"
      :multiple="field.refer?.multiple"
      :collapse-tags="field.refer?.multiple"
      :collapse-tags-tooltip="field.refer?.multiple"
      :show-checkbox="field.refer?.multiple"
      :check-strictly="field.refer?.strict"
  >
    <el-option
        v-for="item in options"
        :label="item.label"
        :value="item.value"
    >
      <m-option :option="item"></m-option>
    </el-option>
  </el-select>
</template>

<script setup lang="ts">
import {computed, onMounted, ref, watch} from "vue";
import type {Meta, MetaField} from "../../../types/tool/meta.types.ts";
import type {DaoTypes} from "../../../types/tool/dao.types.ts";
import {useDao} from "../../../tools/dao.ts";
import {Query} from "../../../tools/query.ts";
import MOption from "../../common/MOption.vue";

const props = defineProps<{
  modelValue: any,
  disabled: boolean,
  db: DaoTypes,
  field: MetaField
}>();
const emits = defineEmits(['update:modelValue'])
const value = computed({
  get: () => props.modelValue,
  set: (v) => emits('update:modelValue', v)
})

const options = ref<any[]>([])
const loading = ref(false)

const meta = ref<Meta>(
    {
      db: props.db,
      entity: props.field.refer?.entity || ''
    }
)
const {find_many} = useDao(meta)

function load() {
  const {includes, excludes, label, value: _value, display} = props.field.refer || {}
  const query = new Query({includes, excludes})
  find_many(query, (payload) => {
    const results = payload.results || []
    const array = results.map(item => {
      return Object.fromEntries([
        ['value', item[_value as string]],
        ['label', item[label as string]],
        ['display', item[display as string]],
      ])
    })
    options.value = array as any[]
  })
}

watch(() => props.field, load, {deep: true})
onMounted(load)

</script>

<style scoped>

</style>